<template>
  <div>
    <el-dialog :visible.sync="detail.open" width="80%" append-to-body :before-close="closeDelDialog" class="demandFormVisible_dialog" >
      <template slot="title">
        <div style="">{{ detail.title }}</div>
      </template>

      <div style="display: flex">
        <div class="headerInfoButton">
          <el-button type="success" plain  @click="addMaterial">添加素材</el-button>
          <el-button type="success" plain  @click="save">保存</el-button>
          <el-button type="danger" plain  @click="reback">返回</el-button>
        </div>
      </div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-tabs type="border-card" class="box-card1jian" v-model="tabsValue">
            <el-tab-pane label="素材列表" name="first">
              <ul class="tablistClass tablist-scroll" style="overflow-y: auto; max-height: 700px;">
                <el-tooltip class="item" v-for="(item, index) in materiadList" :key="index"
                             effect="dark" :content="item.fileName"
                            placement="right">
                  <li :class="activeNameChider == index ? 'chiderAvtia' : ''" class="flex-row-bowtte" @click="onClickInfoTap(item, index)">
                    <p style="width: 300px" class="text-ellipsis">{{ index + 1 }}.{{ item.fileName }}</p>
                    <div>
                      <i class="el-icon-delete" style="cursor: pointer;" @click="onDeleteTap(item)"></i>
                    </div>
                  </li>
                </el-tooltip>
              </ul>
            </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="11">
          <el-card class="box-cardjian">
            <filePreviewTemplate v-if="item && isShow" :item="item" source="bianyan" :istype="1"></filePreviewTemplate>
          </el-card>
        </el-col>
        <el-col :span="7">
          <el-card class="box-cardjian" style="overflow-y: auto;">
            <editor v-model="content" :min-height="660" style="width: 100%" accept=".png, .jpg, .jpeg" :isMaterialListStyle="'1'" :isMaterialList="true" />
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>

    <Material :source="source" @cancel="cancel" @getMaterial="getMaterial" ref="materialRef"></Material>
  </div>

</template>

<script>
import filePreviewTemplate from "@/components/filePreviewTemplate";
import Material from "@/views/archive/bianyan/editTheme/material";
import {getDetailList, saveMaterial, sourceMaterialList} from "@/api/archive/bianyan/editTheme";

export default {
  name: "editDetail",
  // isParams: 1 -- 编辑专题;  2 -- 专题统稿
  props: ['detail', 'isParams'],
  components: {
    Material,
    filePreviewTemplate
  },
  data() {
    return {
      tabsValue: "first", //默认显示第文件类型的第一个
      item: "",
      isShow: true,
      activeNameChider: 0, //初始化切换默认显示
      content: undefined,
      source: {
        title: '',
        open: false
      },
      // 素材id
      materiadList: [],
      materialIds: [],
      archiveIds: []
    }
  },
  created() {
    this.materiadList = []
  },
  methods: {
    init(val) {
      console.log(val,"valceshi")
      if(this.isParams == 1) {
        if(val != undefined) {
          this.content = val.content
          if (val.materialIds != '') {
            this.materialIds = val.materialIds.split(',')
          }
          if (val.archiveIds) {
            this.archiveIds = val.archiveIds.split(',')
          }
          this.form = {
            materialIds: val.materialIds,
            archiveIds: val.archiveIds,
            categoryIds: val.categoryIds
          }
          getDetailList(this.form).then(response=>{
            const materiadList = response.rows.map((item, index) => {
              return {
                id: item.id,
                fileName: item.fileName,
                type: item.type,
                DOC_ID: item.docId,
                path: item.path,
                categoryId: item.categoryId,
                DOC_FILE_TYPE: this.getType(item.fileName),
                index: index
              }
            })
            this.materiadList.push(...materiadList)
            if(this.materiadList.length > 0) {
              this.item = this.materiadList[0];
              this.isShow = true
              // console.log(this.item)
            }
          })
        }
      } else {
        if(val != undefined) {
          if(val.manuscript == null) {
            this.content = val.content
          } else {
            this.content = val.manuscript
          }
          if (val.materialIds != '') {
            this.materialIds = val.materialIds.split(',')
          }
          if (val.archiveIds) {
            this.archiveIds = val.archiveIds.split(',')
          }
          this.form = {
            materialIds: val.materialIds,
            archiveIds: val.archiveIds,
            categoryIds: val.categoryIds
          }
          getDetailList(this.form).then(response=>{
            const materiadList = response.rows.map((item, index) => {
              return {
                id: item.id,
                fileName: item.fileName,
                type: item.type,
                DOC_ID: item.docId,
                path: item.path,
                categoryId: item.categoryId,
                DOC_FILE_TYPE: this.getType(item.fileName),
                index: index
              }
            })
            this.materiadList.push(...materiadList)
            if(this.materiadList.length > 0) {
              this.item = this.materiadList[0];
              this.isShow = true
              // console.log(this.item)
            }
          })
        }
      }
    },
    // 添加素材
    addMaterial() {
      this.$refs.materialRef.activeName = 'personalProfile'
      this.$refs.materialRef.getPersonalProfileList()
      this.source.open = true
      this.source.title = '添加素材'
    },
    // 保存
    save() {
      // console.log(this.content)
      // 编辑专题  状态->1:编辑中
      if(this.isParams == 1) {
        if(this.content == undefined) {
          this.$modal.msgWarning('编辑内容不能为空');
          return;
        }
        const categoryIds = this.materiadList
          .filter(item => item.categoryId !== null)
          .map(item => item.categoryId);
        const archiveIds = this.materiadList
          .filter(item => item.DOC_ID !== null)
          .map(item => item.DOC_ID);
        this.form = {
          content: this.content,
          typeId: this.detail.typeId,
          isKeep: '1',
          state: '1',
          materialIds: this.materialIds.toString(),
          archiveIds: archiveIds.toString(),
          categoryIds: categoryIds.toString()
        }
        saveMaterial(this.form).then(response=>{
          this.$modal.msgSuccess('保存成功')
          this.closeDelDialog()
          this.materiadList = []
          this.materialIds = []
          this.archiveIds = []
          this.item = ''
        })
      } else { // 专题统稿  状态->3:统稿中
        if(this.content == undefined) {
          this.$modal.msgWarning('统稿内容不能为空');
          return;
        }
        const categoryIds = this.materiadList
          .filter(item => item.categoryId !== null)
          .map(item => item.categoryId);
        const archiveIds = this.materiadList
          .filter(item => item.DOC_ID !== null)
          .map(item => item.DOC_ID);
        this.form = {
          manuscript: this.content,
          typeId: this.detail.typeId,
          isKeep: '1',
          state: '3',
          materialIds: this.materialIds.toString(),
          archiveIds: archiveIds.toString(),
          categoryIds: categoryIds.toString()
        }
        console.log(this.form)
        saveMaterial(this.form).then(response=>{
          this.$modal.msgSuccess('保存成功')
          this.closeDelDialog()
          this.materiadList = []
          this.materialIds = []
          this.archiveIds = []
          this.item = ''
        })
      }
    },
    // 返回
    reback() {
      this.$modal.confirm('是否留存素材文件?').then(() => {
        // 编辑专题  状态->1:编辑中
        if(this.isParams == 1) {
          const categoryIds = this.materiadList.map(item => {
            if(item.categoryId != null) {
              return item.categoryId;
            }
          });
          const archiveIds = this.materiadList.map(item => {
            if(item.DOC_ID != null) {
              return item.DOC_ID
            }
          })
          this.form = {
            typeId: this.detail.typeId,
            isKeep: '1',
            state: '1',
            materialIds: this.materialIds.toString(),
            archiveIds: archiveIds.toString(),
            categoryIds: categoryIds.toString()
          }
          saveMaterial(this.form).then(response=>{
            this.$modal.msgSuccess('保存成功')
            this.closeDelDialog()
            this.materiadList = []
            this.materialIds = []
            this.archiveIds = []
            this.item = ''
          })
        } else { // 专题统稿  状态->3:统稿中
          const categoryIds = this.materiadList.map(item => {
            if(item.categoryId != null) {
              return item.categoryId;
            }
          });
          const archiveIds = this.materiadList.map(item => {
            if(item.DOC_ID != null) {
              return item.DOC_ID
            }
          })
          this.form = {
            typeId: this.detail.typeId,
            isKeep: '1',
            state: '3',
            materialIds: this.materialIds.toString(),
            archiveIds: archiveIds.toString(),
            categoryIds: categoryIds.toString()
          }
          saveMaterial(this.form).then(response=>{
            this.$modal.msgSuccess('保存成功')
            this.closeDelDialog()
            this.materiadList = []
            this.materialIds = []
            this.archiveIds = []
            this.item = ''
          })
        }
      }).catch(() => {
        this.materiadList = []
        this.materialIds = []
        this.archiveIds = []
        this.item = ''
        this.closeDelDialog()
      });
    },
    closeDelDialog() {
      var that = this;
      that.$emit("editCancel")
      this.materiadList = []
      this.materialIds = []
      this.archiveIds = []
      this.item = ''
    },
    getMaterial(materialIds, archiveIds) {
      this.source.open = false
      if(materialIds.length != 0) {
        this.materialIds = Array.from(new Set([...this.materialIds, ...materialIds]));
      }
      // 获取所有id
      const allIds = this.materiadList
          .filter(item => item.type == '0')
          .map(item => item.id);
      // 使用Set去除重复id
      var archiveids = [...new Set(allIds)];
      if(archiveIds.length != 0) {
        archiveids = Array.from(new Set([...archiveids, ...archiveIds]));
      }
      console.log(materialIds, archiveIds, this.materialIds, archiveids)
      this.form = {
        materialIds: this.materialIds.toString(),
        archiveIds: archiveids.toString()
      }
      // console.log(form,"liuhaiorng")
      sourceMaterialList(this.form).then(response=>{
        const materiadList = response.rows.map((item, index) => {
          return {
            id: item.id,
            fileName: item.fileName,
            type: item.type,
            DOC_ID: item.docId,
            path: item.path,
            categoryId: item.categoryId,
            DOC_FILE_TYPE: this.getType(item.fileName),
            index: index
          }
        })
        this.materiadList = materiadList
        if(this.materiadList.length > 0) {
          this.item = this.materiadList[0];
          this.isShow = true
        }
      })
    },
    // 获取文件类型
    getType(fileName) {
      let arr = fileName.split('.');
      let result = arr.pop();
      return result;
    },
    cancel() {
      this.source.open = false
    },
    //点击文件 打开对应的文件
    onClickInfoTap(item, index) {
      var that = this;
      that.activeNameChider = index //切换显示数据
      this.item = item
    },
    // 删除素材 -- 页面逻辑删除
    onDeleteTap(data) {
      // console.log(data)
      if(data.type == '1') {
        let index = this.materialIds.indexOf(data.id);
        if(index > -1) {
          this.materialIds.splice(index, 1);
        }
      } else {
        const length = this.materiadList.filter(item => item.id == data.id).length;
        if(length == 1) {
          let index = this.archiveIds.indexOf(data.id);
          if(index > -1) {
            this.archiveIds.splice(index, 1);
          }
        }
      }
      this.materiadList.splice(data.index, 1);
      if (this.materiadList.length > 0) {
        for (let i = 0; i < this.materiadList.length; i++) {
          this.materiadList[i].index = i
        }
      } else {
        this.isShow = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 10px 20px 25px !important;
}

.demandFormVisible_dialog {
  .el-dialog__wrapper {
    pointer-events: none;

    ::v-deep .el-dialog {
      pointer-events: auto;
    }
  }
}

.headerInfoButton {
  position: absolute;
  top: 16px;
  right: 60px;
  margin: 0 10px;
}

.box-card1jian {
  height: 780px;
}

.box-cardjian {
  height: 780px;
  overflow-y: auto;
}

.tablistClass {
  padding: 0px 15px 10px;
}

.tablistClass li {
  height: 40px;
  line-height: 40px;
  font-size: 16px;
}

.flex-row-bowtte {
  display: flex;
  flex-direction: row;
  justify-content: space-between
}

.text-ellipsis {
  overflow: hidden;
  padding: 0;
  margin: 0;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}

.chiderAvtia {
  border-bottom: 1px solid #409EFF;
  color: #409EFF;
}
</style>
